<?php

namespace app\teacher\controller\core;

use app\common\controller\Frontend;
use app\common\enums\AppointmentStatusEnum;
use app\common\model\banxi\core\CoreCourseAppointment as CoreCourseAppointmentModel;
use app\common\model\banxi\learn\LearnSkRecord;
use app\common\model\banxi\organization\Organization;
use app\common\service\course\CourseAppointmentService;
use app\common\service\learn\LearnSkRecordService;
use app\common\service\queue\QueueService;

/*
 * 排课预约
 * */

class CoreCourseAppointment extends Frontend
{
    protected array $noNeedLogin = [''];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }


    /*
     * 查询-我的课表（按天）
     * */
    public function listDayMyCourseAppointment()
    {
        // 获取当前用户ID
        $trainerId = $this->auth->id;

        // 查询符合条件的课程预约记录
        $CoreCourseAppointmentModel = new CoreCourseAppointmentModel();
        $appointments = $CoreCourseAppointmentModel
            ->with([
                'organizationBaseInfo', 'studentInfo',
                'courseInfo' => function ($query) {
                    $query->field('id,gradeId,sentenceGroupEn,sentenceGroupZh,name');
                }])
            ->where('trainerId', $trainerId)
            ->where(function ($query) {
                $query->where('date', '>=', date('Y-m-d'))
                    ->whereOr('appointmentStatus', 'in', [AppointmentStatusEnum::EXPIRED, AppointmentStatusEnum::SK_IN]); // 已过期或上课中
            })
            ->whereNotIn('appointmentStatus',  [AppointmentStatusEnum::CANCEL, AppointmentStatusEnum::END]) // 不为已取消或已结束
            ->order(['date' => 'asc', 'startTime' => 'asc'])
            ->select();

        // 按日期分组
        $groupedData = [];
        foreach ($appointments as &$appointment) {
            $date = $appointment['date'];
            if (!isset($groupedData[$date])) {
                $groupedData[$date] = [
                    'date' => $date,
                    'appointmentList' => []
                ];
            }
            $groupedData[$date]['appointmentList'][] = $appointment;
            if ($appointment['studentOrganizationId'] == 0) {
                $organization = new Organization();
                $appointment['organizationBaseInfo'] = $organization->getOrganizationInfo();
            }
        }
        unset($appointment);

        // 重新索引并按日期排序
        $result = array_values($groupedData);
        usort($result, function ($a, $b) {
            return strcmp($a['date'], $b['date']);
        });

        $this->ok('操作成功', $result);
    }

    /**
     * 查询-我的课表
     *
     * @param string|null $date 日期参数
     * @return \think\response\Json
     */
    public function listMyCourseAppointment()
    {
        $date = $this->request->get('date', null);
        // 获取当前用户ID
        $trainerId = $this->auth->id;

        // 构建查询条件
        $CoreCourseAppointmentModel = new CoreCourseAppointmentModel();
        $query = $CoreCourseAppointmentModel
            ->with([
                'organizationBaseInfo', 'studentInfo',
                'courseInfo' => function ($query) {
                    $query->field('id,gradeId,sentenceGroupEn,sentenceGroupZh,name');
                }])
            ->where('del', 0) // 未删除
            ->where('trainerId', $trainerId)
            ->where(function ($query) {
                $query->where('date', '>=', date('Y-m-d'))
                    ->whereOr('appointmentStatus', 'in', ['5', '2']); // 已过期或上课中
            })
            ->where('appointmentStatus', 'not in', ['3', '4']); // 不为已取消或已结束

        // 如果提供了日期参数，则添加日期筛选条件
        if (!empty($date)) {
            $query->where('date', $date);
        }

        // 排序并查询结果
        $result = $query->order(['date' => 'asc', 'startTime' => 'asc'])
            ->select()
            ->toArray();
        foreach ($result as &$item) {
            if ($item['studentOrganizationId'] == 0) {
                $organization = new Organization();
                $item['organizationBaseInfo'] = $organization->getOrganizationInfo();
            }
        }
        unset($item);

        $this->ok('操作成功', $result);
    }


    /**
     * 查询-我的课表列表
     *
     * @param string|null $date 日期参数
     * @return \think\response\Json
     */
    public function listMyCourseAppointmentList()
    {
        $param = $this->request->post(['index' => 1, 'limit' => 10, 'query']);
        // 获取当前用户ID
        $trainerId = $this->auth->id;
        $param['query']['EQ_trainerId'] = $trainerId;
        $where = get_query($param);
        $pageParams = get_page_params($param);

        // 构建查询条件
        $CoreCourseAppointmentModel = new CoreCourseAppointmentModel();
        $query = $CoreCourseAppointmentModel
            ->with(['organizationBaseInfo', 'studentInfo'])
            ->where($where)
            ->where(function ($query) {
                $query->where('date', '>=', date('Y-m-d'))
                    ->whereOr('appointmentStatus', 'in', ['5', '2']); // 已过期或上课中
            })
            ->where('appointmentStatus', 'not in', ['3', '4']); // 不为已取消或已结束

        // 排序并查询结果
        $result = $query->order(['date' => 'desc', 'startTime' => 'desc'])
            ->paginate([
                'page' => $pageParams['page'],
                'list_rows' => $pageParams['limit']
            ])->each(function ($item) {
                if ($item['studentOrganizationId'] == 0) {
                    $organization = new Organization();
                    $item['organizationBaseInfo'] = $organization->getOrganizationInfo();
                }
            });

        $this->ok('操作成功', result_row($result));
    }

    /*
     * 开始上课
     * */
    public function startSk()
    {
        $id = $this->request->post('id', 0);

        $trainerId = $this->auth->id;
        $LearnSkRecordService = new LearnSkRecordService();
        $res = $LearnSkRecordService->startSk($trainerId, $id);
        //自动结束课程
        $queueService = new QueueService();
        $delay = strtotime($res['endTime']) - time();
        $queueService->addEndSkJob([
            'recordId' => $res['recordId']
        ], $delay);

        $this->ok('操作成功');
    }

    /*
     * 结束上课
     * */
    public function endSk()
    {
        $id = $this->request->post('id', 0);

        $trainerId = $this->auth->id;
        $LearnSkRecordService = new LearnSkRecordService();
        $result = $LearnSkRecordService->endSk($trainerId, $id);
        if (!$result) {
            $this->fail($LearnSkRecordService->getError());
        }
        $this->ok('操作成功');
    }

    /**
     * 查询-上课预计结束时间
     */
    public function getSkEndTime()
    {
        $appointmentId = $this->request->get('appointmentId', 0);

        // 查询上课记录中的结束时间
        $LearnSkRecordModel = new LearnSkRecord();
        $endTime = $LearnSkRecordModel
            ->where('appointmentId', $appointmentId)
            ->value('endTime');
        $endTime = empty($endTime) ? null : $endTime;

        $this->ok('操作成功', $endTime);
    }

    /*
     * 根据预约ID查询上课记录信息
     * */
    public function getSkrecordInfoByAppointmentId()
    {
        $appointmentId = $this->request->get('appointmentId', 0);

        // 查询上课记录中的结束时间
        $LearnSkRecordModel = new LearnSkRecord();
        $record = $LearnSkRecordModel
            ->where('appointmentId', $appointmentId)
            ->find();

        $this->ok('操作成功', $record);
    }


    /*
     * 老师创建预约-时间优先
     */
    public function teacherAppointment()
    {
        $param = $this->request->param();
        $courseAppointmentService = new CourseAppointmentService();
        $trainerId = $this->auth->id;
        if (!$this->auth->isAppointment) {
            $this->fail('你没有预约权限');
        }
        $param['trainerId'] = $trainerId;
        $res = $courseAppointmentService->timeAppointment($param);
        if (!$res) {
            $this->fail($courseAppointmentService->getError());
        }
        $this->ok('操作成功');
    }

    /*
     * 修改预约
     */
    public function updateAppointment()
    {
        $param = $this->request->param();
        $trainerId = $this->auth->id;
        $param['trainerId'] = $trainerId;
        if (!$this->auth->isAppointment) {
            $this->fail('你没有预约权限');
        }
        $courseAppointmentService = new CourseAppointmentService();
        $res = $courseAppointmentService->updateAppointment($param);
        if (!$res) {
            $this->fail($courseAppointmentService->getError());
        }
        $this->ok();
    }

    /*
     * 取消预约
     */
    public function cancelAppointment()
    {
        $param = $this->request->param();
        if (!$this->auth->isAppointment) {
            $this->fail('你没有预约权限');
        }
        $courseAppointmentService = new CourseAppointmentService();
        $res = $courseAppointmentService->cancelAppointment($param);
        if (!$res) {
            $this->fail($courseAppointmentService->getError());
        }
        $this->ok();
    }
}